package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.constant.UserParamConst;
import cn.net.shuxing.yifu.common.constant.UserState;
import cn.net.shuxing.yifu.common.constant.UserType;
import cn.net.shuxing.yifu.common.dto.WalletMemberCoinListDto;
import cn.net.shuxing.yifu.common.dto.WalletShareholderCoinListDto;
import cn.net.shuxing.yifu.common.mapper.CoinTypeMapper;
import cn.net.shuxing.yifu.common.util.CommonExample;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.RedisKeyCreator;
import cn.net.shuxing.yifu.common.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoinTypeService extends BaseService<CoinType, CoinTypeMapper> {
    @Autowired
    private ShareholderBuyGrantHistoryService shareholderBuyGrantHistoryService;

    @Autowired
    private AliveCoinActivateHistoryService aliveCoinActivateHistoryService;

    @Autowired
    private DealParamService dealParamService;

    @Autowired
    private CashWalletService cashWalletService;

    @Autowired
    private UserCapitalService userCapitalService;

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private DealHistoryService dealHistoryService;

    @Autowired
    private CoinRatioService coinRatioService;

    @Autowired
    private OssCommonService ossCommonService;

    @Autowired
    private OpenPriceHistoryService openPriceHistoryService;

    @Autowired
    CoinTypeMapper coinTypeMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDealHistoryService userDealHistoryService;

    public void inserCoinType(String coinTypeaName, String icon) {
        CoinType coinType = new CoinType();
        coinType.setName(coinTypeaName);
        coinType.setIcon(icon);
//        System.out.print(coinType.getName() + "," + coinType.getCreateTime().toString() + "," + coinType.getUpdateTime().toString());
//        System.out.println();
        mapper.insertSelective(coinType);
    }

    public CoinType getByCoinTypeName(String name) {
        CommonExample example = new CommonExample(CoinType.class);
        example.equals("name", name);
        return getByExample(example);
    }

    @Override
    public CoinType getByPrimaryKey(Object key) {
        //Jedis //jedis = jedisUtil.getJedis();
        String coinTypeStr = jedisUtil.get(RedisKeyCreator.coinType((int) key));
        if (!StringUtils.hasText(coinTypeStr)) {
            CoinType coinType = super.getByPrimaryKey(key);
            jedisUtil.set(RedisKeyCreator.coinType(coinType.getId()), JSON.toJSONString(coinType));
            //jedisUtil.close();
            coinType.setIconUrl(ossCommonService.getUrl(OssConstant.ossBucketName, coinType.getIcon()));
            return coinType;
        }
        CoinType coinType = JSON.parseObject(coinTypeStr, CoinType.class);
        coinType.setNewestPrice(openPriceHistoryService.getOpenPrice((int) key));
        coinType.setIconUrl(ossCommonService.getUrl(OssConstant.ossBucketName, coinType.getIcon()));
        coinType.setCoinGain(coinRatioService.calculateCoinGain(coinType.getId()));
        return coinType;
    }

    @Override
    protected void complete(CoinType bean) {
        if (bean == null)
            return;
        BigDecimal coinGain = coinRatioService.calculateCoinGain(bean.getId());
        BigDecimal newestPrice = openPriceHistoryService.getOpenPrice(bean.getId());
        bean.setNewestPrice(newestPrice);
        bean.setCoinGain(coinGain);

        List<UserDealHistory> dealHistoryList = userDealHistoryService.getsYestodayByCoinCount(bean.getId());
        BigDecimal dealAliveCoinCount = new BigDecimal(0);
        for (UserDealHistory dealHistory : dealHistoryList) {
            dealAliveCoinCount = dealAliveCoinCount.add(dealHistory.getDealAliveCoinCount());
        }
        bean.setTodayDealCount(dealAliveCoinCount);

        bean.setNewestPrice(newestPrice);
        jedisUtil.set(RedisKeyCreator.coinType(bean.getId()), JSON.toJSONString(bean));
    }

    public List<CoinType> searchByName(String name) {
        Example example = new Example(CoinType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.orLike("name", "%" + name + "%");
        criteria.orLike("simpleName", "%" + name + "%");
        criteria.andEqualTo("deleted", '0');
        example.and(criteria);
        return coinTypeMapper.selectByExample(example);
    }

    public CoinType getByCoinTypeSimpleName(String coinTypeSimpleName) {
        CommonExample example = new CommonExample(CoinType.class);
        Example.Criteria criteria = example.getCriteria();
        criteria.andLike("name", "%" + coinTypeSimpleName + "%");
        try {
            CoinType coinType = getByExampleWithoutComplete(example);
            return coinType;
        } catch (Exception e) {
            List<CoinType> coinTypeList = getsByExample(example);
            if (coinTypeList != null && !coinTypeList.isEmpty())
                return coinTypeList.get(0);
            else
                return null;
        }
    }

    @Override
    public List<CoinType> getAll() {
        List<CoinType> all = super.getAll();
        return all;
    }

    @Override
    public int update(CoinType bean) {
        if (bean == null)
            return -1;
        if (super.update(bean) < 1) {
            return -1;
        } else {
            jedisUtil.set(RedisKeyCreator.coinType(bean.getId()), JSON.toJSONString(bean));
            return 1;
        }
    }

    public List<WalletMemberCoinListDto> getMemberCoinListDto(Integer userId) {
        WalletMemberCoinListDto walletMemberCoinListDto = new WalletMemberCoinListDto();
        ArrayList<WalletMemberCoinListDto> walletMemberCoinListDtoList = new ArrayList<>();
        User user = userService.getByPrimaryKey(userId);
        //获取现金钱包信息
        CashWallet cashWallet = cashWalletService.getByUserId(userId);
        //获取公价
        BigDecimal openPrice = new BigDecimal(jedisUtil.get(RedisKeyCreator.openPrice(1)));
        BigDecimal divide = cashWallet.getCashCount().divide(openPrice, 8, BigDecimal.ROUND_HALF_UP);
        BigDecimal newDivide = divide.setScale(8, BigDecimal.ROUND_HALF_UP);
        walletMemberCoinListDto.setName("CNY");
        walletMemberCoinListDto.setSimpleName("人民币");
        walletMemberCoinListDto.setCurrentFronzenCount(new BigDecimal(0));
        walletMemberCoinListDto.setCurrentUsAbleCount(cashWallet.getCashCount());
        walletMemberCoinListDto.setConvertCount(newDivide);
        walletMemberCoinListDtoList.add(walletMemberCoinListDto);

        List<CoinType> all = getAll();
        if (all != null && !all.isEmpty()) {
            if (user.getType() != UserType.NONE) {
                for (CoinType coinType : all) {
                    walletMemberCoinListDto.setName(coinType.getName());
                    walletMemberCoinListDto.setSimpleName(coinType.getSimpleName());
                    //获取用户单币种钱包
                    UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinType.getId(), UserType.MEMBER);
                    walletMemberCoinListDto.setConvertCount(userCapital.getAliveCoinCount().multiply(openPrice));

                    if (user.getState() != UserState.OK) {
                        walletMemberCoinListDto.setCurrentUsAbleCount(new BigDecimal(0));
                        walletMemberCoinListDto.setCurrentFronzenCount(userCapital.getAliveCoinCount());
                    } else {
                        //获取交易钱包最低持有量
                        BigDecimal minCount = new BigDecimal(dealParamService.getValue(userId, userCapital.getCoinTypeId(), UserParamConst.MEMBER_KEEP_ALIVE_COIN_MIN_COUNT));
                        walletMemberCoinListDto.setCurrentUsAbleCount(userCapital.getAliveCoinCount().subtract(minCount));
                        walletMemberCoinListDto.setCurrentFronzenCount(minCount);
                    }
                    walletMemberCoinListDtoList.add(walletMemberCoinListDto);
                }
            }
        }
        return walletMemberCoinListDtoList;
    }

    public List<WalletShareholderCoinListDto> getShareholderCoinListDto(Integer userId) {
        WalletShareholderCoinListDto walletShareholderCoinListDto = new WalletShareholderCoinListDto();
        ArrayList<WalletShareholderCoinListDto> walletShareholderCoinListDtoList = new ArrayList<>();
        User user = userService.getByPrimaryKey(userId);
        //获取现金钱包信息
        CashWallet cashWallet = cashWalletService.getByUserId(userId);
        //获取公价
        BigDecimal openPrice = new BigDecimal(jedisUtil.get(RedisKeyCreator.openPrice(1)));
        BigDecimal divide = cashWallet.getCashCount().divide(openPrice, 8, BigDecimal.ROUND_HALF_UP);
        BigDecimal newDivide = divide.setScale(8, BigDecimal.ROUND_HALF_UP);
        walletShareholderCoinListDto.setName("CNY");
        walletShareholderCoinListDto.setSimpleName("人民币");
        walletShareholderCoinListDto.setCurrentFronzenCount(new BigDecimal(0));
        walletShareholderCoinListDto.setCurrentUsAbleCount(cashWallet.getCashCount());
        walletShareholderCoinListDto.setCoinGrantCount(newDivide);
        walletShareholderCoinListDtoList.add(walletShareholderCoinListDto);

        List<CoinType> all = getAll();
        if (all != null && !all.isEmpty()) {
            for (CoinType coinType : all) {
                walletShareholderCoinListDto.setName(coinType.getName());
                walletShareholderCoinListDto.setSimpleName(coinType.getSimpleName());
                //获取用户单币种钱包
                UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinType.getId(), UserType.MEMBER);
                //当前可用=0 当前冻结= 活币+休眠币
                if (user.getState() != UserState.OK) {
                    walletShareholderCoinListDto.setCurrentUsAbleCount(new BigDecimal(0));
                    walletShareholderCoinListDto.setCurrentFronzenCount(userCapital.getAliveCoinCount().add(userCapital.getSleepCoinCount()));
                    //当前可用= 活币  当前冻结=休眠币
                } else {
                    walletShareholderCoinListDto.setCurrentUsAbleCount(userCapital.getAliveCoinCount());
                    walletShareholderCoinListDto.setCurrentFronzenCount(userCapital.getSleepCoinCount());
                }
                BigDecimal totalGrantCount = shareholderBuyGrantHistoryService.getTotalGrantCount(userId, coinType.getId());
                walletShareholderCoinListDto.setCoinGrantCount(totalGrantCount);
                walletShareholderCoinListDto.setCoinGrantConvert(totalGrantCount.multiply(openPrice));
                walletShareholderCoinListDtoList.add(walletShareholderCoinListDto);
            }
        }
        return walletShareholderCoinListDtoList;
    }

    public void increase() {
        List<CoinType> all = getAll();
        if (all != null && !all.isEmpty()) {
            for (CoinType coinType : all) {
                Integer coinTypeId = coinType.getId();
                BigDecimal increaseRatio = coinRatioService.calculateCoinGain(coinTypeId);
                BigDecimal oldPrice = new BigDecimal(jedisUtil.get(RedisKeyCreator.openPrice(coinTypeId)));
                BigDecimal newPrice = oldPrice.multiply(increaseRatio);
                jedisUtil.set(RedisKeyCreator.openPrice(coinTypeId),newPrice.toString());
                OpenPriceHistory openPriceHistory = new OpenPriceHistory();
                openPriceHistory.setCoinTypeId(coinTypeId);
                openPriceHistory.setOpenPrice(newPrice);
                openPriceHistoryService.insert(openPriceHistory);
            }
        }
    }
}
